<?php


namespace app\common\controller;



use think\facade\Request;

class ApiBase extends CommonBase
{
    public function __construct()
    {
        parent::__construct();
        //$this->checkUserStatus();
    }

    protected $user=null;

    /**
     * 获取当前登录的用户
     *
     * @return \app\common\model\Admin
     */
    protected function getUser(){
        if(!$this->user){
            $admin=\app\common\model\User::getModelByToken();
            $this->user = $admin;
        }
        return $this->user;
    }



    public function checkUser(){
        $user = $this->getUser();
        if(!$user){
            $this->error("请先登录",101);
        }
    }


    /**
     * 权限判断
     * @param $check_code
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function checkRoleCode($check_code){
        $admin = $this->getUser();
        if (empty($admin)){
            return returnFormat(999,'检查权限失败，未获取到登录用户');
        }

        if ($admin['is_root'] == 1){
            return returnFormat(0,'检查成功');
        }

        $admin_role_id = $admin->admin_role_id;
        $admin_role = \app\common\model\AdminRole::find($admin_role_id);
        if (empty($admin_role)){
            return returnFormat(999,'检查权限失败，未获取到用户的角色');
        }

        $codes = $admin_role->codes;
        $code_array = explode(',',$codes);

        foreach ($code_array as $code){
            if ($check_code == $code && $check_code != ''){
                return returnFormat(0,'检查成功');
            }
        }

        $res = [];
        $res['admin'] = $admin;
        return returnFormat(999,'用户无权限',$res);
    }

    /**
     * byte数值显示用的格式
     * @param $byte
     * @return string
     */
    public function trans_byte($byte){
        $KB = 1024;

        $MB = 1024 * $KB;

        $GB = 1024 * $MB;

        $TB = 1024 * $GB;

        if ($byte < $KB) {

            return $byte . "B";

        } elseif ($byte < $MB) {

            return round($byte / $KB, 2) . "KB";

        } elseif ($byte < $GB) {

            return round($byte / $MB, 2) . "MB";

        } elseif ($byte < $TB) {

            return round($byte / $GB, 2) . "GB";

        } else {

            return round($byte / $TB, 2) . "TB";

        }
    }



    /**
     * action对应权限代码
     * @return array
     */
    protected function getPermissionActions(){
        return [
        ];
    }

    /**
     * 统一权限校验
     */
    protected function checkPermission(){
        $action = \request()->action(true);
        $permissionActions=$this->getPermissionActions();
        if(isset($permissionActions[$action])){
            $role=$permissionActions[$action];
            $res=$this->checkRoleCode($role);
            if($res["code"]!==0){
                $this->error($res["msg"]);
            }
        }
    }

}
